package com.csea.common.utils;

import com.coze.openapi.service.auth.JWTOAuth;
import com.coze.openapi.service.auth.JWTOAuthClient;
import com.coze.openapi.service.service.CozeAPI;
import com.csea.common.config.CozeConfig;
import jakarta.annotation.PostConstruct;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Component
@Slf4j
public class CozeUtil {
    @Autowired
    private ResourceLoader resourceLoader;
    @Autowired
    private CozeConfig cozeConfig;

    private CozeAPI cozeAPI;

    //健康状态标记
    @Getter
    private boolean initialized = false;

    // 重构初始化方法
    @PostConstruct
    public synchronized void init() {
        try {
            JWTOAuthClient authClient = createJWTOAuthClient();
            if (authClient != null) {
                this.cozeAPI = buildCozeAPI(authClient);
                this.initialized = true;
                log.info("Coze客户端初始化成功");
            }
        } catch (RuntimeException e) {
            log.error("Coze客户端初始化失败", e);
            this.initialized = false;
        }
    }

    // 重构 API 构建逻辑
    private CozeAPI buildCozeAPI(JWTOAuthClient authClient) {
        return new CozeAPI.Builder()
                .auth(JWTOAuth.builder().jwtClient(authClient).build())
                .baseURL(cozeConfig.getApiBase())
                .connectTimeout(30000)
                .readTimeout(30000)
                .build();
    }

    // 重构认证客户端创建方法
    public JWTOAuthClient createJWTOAuthClient() {
        try {
            Resource resource = resourceLoader.getResource(cozeConfig.getPrivateKeyFilePath());

            if (!resource.exists()) {
                throw new RuntimeException("私钥文件路径错误: " + cozeConfig.getPrivateKeyFilePath());
            }

            String privateKey = readAndValidatePrivateKey(resource);
            return buildJWTOAuthClient(privateKey);

        } catch (IOException e) {
            throw new IllegalStateException("读取私钥文件失败", e);
        } catch (Exception e) {
            throw new RuntimeException("创建认证客户端失败", e);
        }
    }

    // 私钥读取校验方法
    private String readAndValidatePrivateKey(Resource resource) throws IOException {
        String keyContent = resource.getContentAsString(StandardCharsets.UTF_8);
        if (keyContent.isBlank()) {
            throw new IOException("私钥文件为空");
        }
        return keyContent.trim();
    }

    // 认证客户端构建方法
    private JWTOAuthClient buildJWTOAuthClient(String privateKey) throws Exception {
        return new JWTOAuthClient.JWTOAuthBuilder()
                .clientID(cozeConfig.getClientId())
                .privateKey(privateKey)
                .publicKey(cozeConfig.getPublicKeyId())
                .baseURL(cozeConfig.getApiBase())
                .build();
    }

    // 安全获取 API 的方法
    public CozeAPI getCozeAPI() {
        if (!initialized) {
            throw new IllegalStateException("CozeAPI 未初始化");
        }
        return cozeAPI;
    }
}
